/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.services;

import utsc.apps.utschedule.UTSCheduleApp;
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

/**
 * A simple service that refreshes the underlying data cache.
 */
public class TimetableDataService extends IntentService {

	public static final int REFRESH_COURSES=1;
	public static final int REFRESH_ASSIGNMENT=2;
	public static final int REFRESH_EXAM=3;
	
	public static final String REQUEST_REFRESH="refreshType";
	public static final String REQUEST_ASSIGNMENT="assignmentId";
	public static final String REQUEST_COURSE="courseId";
	public static final String REQUEST_EXAM="examId";
	
	public static final String SERVICE_NAME="utsc.apps.utschedule.services.TimetableDataService";
	
	public static final String ACTION_COURSES="refresh_courses";
	public static final String ACTION_ASSIGNMENT="refresh_assignment";
	public static final String ACTION_EXAM="refresh_exam";
	
	public TimetableDataService() {
		super(SERVICE_NAME);
	}

	@Override
	protected void onHandleIntent(Intent arg0) {
		int refreshType=arg0.getIntExtra(REQUEST_REFRESH, 0);
		Intent in=null;
		UTSCheduleApp app=(UTSCheduleApp) getApplication();
		switch (refreshType) {
		case REFRESH_COURSES:
			in=new Intent(ACTION_COURSES);
			int refreshCourse=arg0.getIntExtra(REQUEST_COURSE, 0);
		    in.putExtra(REQUEST_COURSE, refreshCourse);
	        app.refreshCurrentTimetable();
	        app.get_currentActiveTimetable().refreshCourseList();
			break;
		case REFRESH_ASSIGNMENT:
			in=new Intent(ACTION_ASSIGNMENT);
	        int refreshAssignment=arg0.getIntExtra(REQUEST_ASSIGNMENT, 0);
	        in.putExtra(REQUEST_ASSIGNMENT, refreshAssignment);
			break;
		case REFRESH_EXAM:
			in = new Intent(ACTION_EXAM);
			int refreshExam=arg0.getIntExtra(REQUEST_EXAM, 0);
			in.putExtra(REQUEST_EXAM, refreshExam);
			break;
		default:
			break;
		}
		
        LocalBroadcastManager.getInstance(this).sendBroadcast(in);
	}

}
